<template>
  <div class="ai-assistant">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">AI智能助手</h1>
      <p class="page-subtitle">多模态AI交互，为您提供专业的母婴护理建议</p>
    </div>

    <!-- 功能导航 -->
    <div class="function-nav">
      <div class="nav-tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.key"
          :class="['nav-tab', { active: activeTab === tab.key }]"
          @click="activeTab = tab.key"
        >
          <component :is="tab.icon" class="w-5 h-5" />
          {{ tab.label }}
        </button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 智能对话 -->
      <div v-if="activeTab === 'chat'" class="tab-content">
        <div class="chat-container">
          <div class="chat-messages" ref="chatMessages">
            <div v-for="message in chatMessages" :key="message.id" :class="['message', message.role]">
              <div class="message-avatar">
                <component :is="message.role === 'user' ? 'User' : 'Bot'" class="w-8 h-8" />
              </div>
              <div class="message-content">
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                <div v-if="message.suggestions && message.suggestions.length > 0" class="message-suggestions">
                  <button 
                    v-for="suggestion in message.suggestions" 
                    :key="suggestion"
                    class="suggestion-btn"
                    @click="sendMessage(suggestion)"
                  >
                    {{ suggestion }}
                  </button>
                </div>
              </div>
            </div>
            <div v-if="isTyping" class="message assistant typing">
              <div class="message-avatar">
                <Bot class="w-8 h-8" />
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="chat-input-area">
            <div class="input-container">
              <input 
                v-model="chatInput" 
                type="text" 
                placeholder="请输入您的问题..." 
                class="chat-input"
                @keypress.enter="sendMessage()"
                :disabled="isTyping"
              />
              <button 
                class="voice-btn"
                :class="{ recording: isRecording }"
                @click="toggleVoiceRecording"
              >
                <Mic class="w-5 h-5" />
              </button>
              <button 
                class="send-btn"
                @click="sendMessage()"
                :disabled="!chatInput.trim() || isTyping"
              >
                <Send class="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 图像识别 -->
      <div v-if="activeTab === 'image'" class="tab-content">
        <div class="image-recognition">
          <div class="upload-area">
            <div class="upload-zone" @click="triggerImageUpload" @drop="handleImageDrop" @dragover.prevent>
              <input 
                ref="imageInput" 
                type="file" 
                accept="image/*" 
                @change="handleImageUpload" 
                style="display: none;"
              />
              <div v-if="!selectedImage" class="upload-placeholder">
                <Camera class="w-12 h-12 text-gray-400 mb-4" />
                <p class="text-lg text-gray-600 mb-2">点击或拖拽上传图片</p>
                <p class="text-sm text-gray-500">支持 JPG、PNG、GIF 格式</p>
              </div>
              <div v-else class="image-preview">
                <img :src="selectedImage" alt="预览图片" class="preview-img" />
                <button class="remove-image" @click.stop="removeImage">
                  <X class="w-4 h-4" />
                </button>
              </div>
            </div>
          </div>
          
          <div class="recognition-options">
            <div class="option-tabs">
              <button 
                v-for="option in imageOptions" 
                :key="option.key"
                :class="['option-tab', { active: selectedImageOption === option.key }]"
                @click="selectedImageOption = option.key"
              >
                <component :is="option.icon" class="w-4 h-4" />
                {{ option.label }}
              </button>
            </div>
            
            <button 
              class="analyze-btn"
              @click="analyzeImage"
              :disabled="!selectedImage || isAnalyzing"
            >
              <Zap class="w-4 h-4" />
              {{ isAnalyzing ? '分析中...' : '开始分析' }}
            </button>
          </div>
          
          <div v-if="imageResult" class="analysis-result">
            <h3 class="result-title">分析结果</h3>
            <div class="result-content">
              <!-- 通用识别结果 -->
              <div v-if="selectedImageOption === 'general'" class="general-result">
                <div v-if="imageResult.objects && imageResult.objects.length > 0" class="objects-section">
                  <h4 class="section-title">识别物体</h4>
                  <div class="objects-grid">
                    <div v-for="obj in imageResult.objects" :key="obj.name" class="object-item">
                      <span class="object-name">{{ obj.name }}</span>
                      <span class="object-confidence">{{ (obj.confidence * 100).toFixed(1) }}%</span>
                    </div>
                  </div>
                </div>
                
                <div v-if="imageResult.scene" class="scene-section">
                  <h4 class="section-title">场景描述</h4>
                  <p class="scene-description">{{ imageResult.scene.description }}</p>
                  <div class="scene-tags">
                    <span v-for="tag in imageResult.scene.tags" :key="tag" class="scene-tag">{{ tag }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 产品识别结果 -->
              <div v-if="selectedImageOption === 'product'" class="product-result">
                <div class="product-info">
                  <h4 class="product-name">{{ imageResult.product_name }}</h4>
                  <p class="product-category">分类: {{ imageResult.category }}</p>
                  <p v-if="imageResult.brand" class="product-brand">品牌: {{ imageResult.brand }}</p>
                  <p class="product-confidence">识别准确度: {{ (imageResult.confidence * 100).toFixed(1) }}%</p>
                </div>
                
                <div v-if="imageResult.similar_products" class="similar-products">
                  <h4 class="section-title">相似产品推荐</h4>
                  <div class="products-grid">
                    <div v-for="product in imageResult.similar_products" :key="product.name" class="product-card">
                      <img :src="product.image_url" :alt="product.name" class="product-image" />
                      <div class="product-details">
                        <h5 class="product-title">{{ product.name }}</h5>
                        <p class="product-price">{{ product.price_range }}</p>
                        <div class="product-rating">
                          <Star class="w-4 h-4 text-yellow-400" />
                          <span>{{ product.rating }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div v-if="imageResult.safety_info" class="safety-info">
                  <h4 class="section-title">安全信息</h4>
                  <p class="safety-age">适用年龄: {{ imageResult.safety_info.age_appropriate }}</p>
                  <p class="safety-rating">安全评级: {{ imageResult.safety_info.safety_rating }}/5</p>
                  <div v-if="imageResult.safety_info.warnings.length > 0" class="safety-warnings">
                    <h5 class="warnings-title">注意事项:</h5>
                    <ul class="warnings-list">
                      <li v-for="warning in imageResult.safety_info.warnings" :key="warning">{{ warning }}</li>
                    </ul>
                  </div>
                </div>
              </div>
              
              <!-- 症状识别结果 -->
              <div v-if="selectedImageOption === 'symptoms'" class="symptoms-result">
                <div v-if="imageResult.urgent_care_needed" class="urgent-warning">
                  <AlertTriangle class="w-6 h-6 text-red-500" />
                  <span class="urgent-text">建议立即就医</span>
                </div>
                
                <div v-if="imageResult.possible_conditions" class="conditions-section">
                  <h4 class="section-title">可能的情况</h4>
                  <div class="conditions-list">
                    <div v-for="condition in imageResult.possible_conditions" :key="condition.name" class="condition-item">
                      <div class="condition-header">
                        <h5 class="condition-name">{{ condition.name }}</h5>
                        <span :class="['severity-badge', condition.severity]">{{ getSeverityText(condition.severity) }}</span>
                      </div>
                      <p class="condition-description">{{ condition.description }}</p>
                      <div class="condition-recommendations">
                        <h6 class="recommendations-title">建议:</h6>
                        <ul class="recommendations-list">
                          <li v-for="rec in condition.recommendations" :key="rec">{{ rec }}</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="disclaimer">
                  <Info class="w-5 h-5 text-blue-500" />
                  <p class="disclaimer-text">{{ imageResult.disclaimer }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 语音处理 -->
      <div v-if="activeTab === 'voice'" class="tab-content">
        <div class="voice-processing">
          <div class="voice-recorder">
            <div class="recorder-container">
              <div :class="['record-button', { recording: isRecording, processing: isProcessingVoice }]" @click="toggleRecording">
                <Mic class="w-8 h-8" />
              </div>
              <p class="record-status">
                {{ isRecording ? '正在录音...' : isProcessingVoice ? '处理中...' : '点击开始录音' }}
              </p>
              <div v-if="recordingTime > 0" class="recording-time">
                {{ formatRecordingTime(recordingTime) }}
              </div>
            </div>
          </div>
          
          <div class="voice-options">
            <div class="option-group">
              <label class="option-label">语言选择</label>
              <select v-model="voiceLanguage" class="option-select">
                <option value="zh-CN">中文</option>
                <option value="en-US">英文</option>
              </select>
            </div>
          </div>
          
          <div v-if="voiceResult" class="voice-result">
            <h3 class="result-title">识别结果</h3>
            <div class="transcript-container">
              <p class="transcript-text">{{ voiceResult.transcript }}</p>
              <p class="transcript-confidence">准确度: {{ (voiceResult.confidence * 100).toFixed(1) }}%</p>
            </div>
            
            <div v-if="voiceResult.segments" class="segments-container">
              <h4 class="segments-title">分段结果</h4>
              <div class="segments-list">
                <div v-for="segment in voiceResult.segments" :key="segment.start_time" class="segment-item">
                  <span class="segment-time">{{ formatTime(segment.start_time) }} - {{ formatTime(segment.end_time) }}</span>
                  <span class="segment-text">{{ segment.text }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 文字转语音 -->
          <div class="tts-section">
            <h3 class="section-title">文字转语音</h3>
            <div class="tts-input-area">
              <textarea 
                v-model="ttsText" 
                placeholder="输入要转换为语音的文字..." 
                class="tts-textarea"
              ></textarea>
              <div class="tts-options">
                <div class="option-group">
                  <label class="option-label">声音</label>
                  <select v-model="ttsVoice" class="option-select">
                    <option value="female">女声</option>
                    <option value="male">男声</option>
                    <option value="child">童声</option>
                  </select>
                </div>
                <div class="option-group">
                  <label class="option-label">语速</label>
                  <input v-model="ttsSpeed" type="range" min="0.5" max="2" step="0.1" class="option-range" />
                  <span class="range-value">{{ ttsSpeed }}x</span>
                </div>
              </div>
              <button class="generate-speech-btn" @click="generateSpeech" :disabled="!ttsText.trim() || isGeneratingSpeech">
                <Volume2 class="w-4 h-4" />
                {{ isGeneratingSpeech ? '生成中...' : '生成语音' }}
              </button>
            </div>
            
            <div v-if="generatedAudio" class="audio-player">
              <audio :src="generatedAudio.audio_url" controls class="audio-control"></audio>
              <p class="audio-info">时长: {{ generatedAudio.duration }}秒</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 图像生成 -->
      <div v-if="activeTab === 'generate'" class="tab-content">
        <div class="image-generation">
          <div class="generation-form">
            <div class="form-group">
              <label class="form-label">描述提示词</label>
              <textarea 
                v-model="generatePrompt" 
                placeholder="描述您想要生成的图像，例如：一个可爱的婴儿房间，温馨的色调，现代简约风格" 
                class="form-textarea"
              ></textarea>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">风格</label>
                <select v-model="generateStyle" class="form-select">
                  <option value="realistic">写实</option>
                  <option value="cartoon">卡通</option>
                  <option value="sketch">素描</option>
                  <option value="watercolor">水彩</option>
                </select>
              </div>
              
              <div class="form-group">
                <label class="form-label">尺寸</label>
                <select v-model="generateSize" class="form-select">
                  <option value="square">正方形</option>
                  <option value="portrait">竖版</option>
                  <option value="landscape">横版</option>
                </select>
              </div>
              
              <div class="form-group">
                <label class="form-label">质量</label>
                <select v-model="generateQuality" class="form-select">
                  <option value="standard">标准</option>
                  <option value="hd">高清</option>
                </select>
              </div>
            </div>
            
            <button 
              class="generate-btn"
              @click="generateImage"
              :disabled="!generatePrompt.trim() || isGenerating"
            >
              <Sparkles class="w-4 h-4" />
              {{ isGenerating ? '生成中...' : '生成图像' }}
            </button>
          </div>
          
          <div v-if="generatedImages && generatedImages.length > 0" class="generated-images">
            <h3 class="result-title">生成结果</h3>
            <div class="images-grid">
              <div v-for="(image, index) in generatedImages" :key="index" class="generated-image">
                <img :src="image.url" :alt="`生成图像 ${index + 1}`" class="generated-img" />
                <div class="image-actions">
                  <button class="action-btn" @click="downloadImage(image.url)">
                    <Download class="w-4 h-4" />
                    下载
                  </button>
                  <button class="action-btn" @click="shareImage(image.url)">
                    <Share class="w-4 h-4" />
                    分享
                  </button>
                </div>
              </div>
            </div>
            <p class="generation-info">生成时间: {{ generationTime }}秒</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { multimodalAIService } from '@/services/multimodalAIService';

// 创建toast对象
const toast = {
  success: (message: string) => {
    uni.showToast({ title: message, icon: 'success' });
  },
  error: (message: string) => {
    uni.showToast({ title: message, icon: 'error' });
  }
};

@Component
export default class AIAssistant extends Vue {
  // 响应式数据
  activeTab: string = 'chat';
  chatMessages: any[] = [];
  chatInput: string = '';
  isTyping: boolean = false;
  isRecording: boolean = false;

  // 图像识别相关
  selectedImage: string | null = null;
  selectedImageOption: string = 'general';
  imageResult: any = null;
  isAnalyzing: boolean = false;
  imageInput: HTMLInputElement | null = null;

  // 语音处理相关
  voiceResult: any = null;
  isProcessingVoice: boolean = false;
  recordingTime: number = 0;
  voiceLanguage: string = 'zh-CN';
  mediaRecorder: MediaRecorder | null = null;
  audioChunks: Blob[] = [];
  recordingInterval: any = null;

  // 文字转语音相关
  ttsText: string = '';
  ttsVoice: string = 'female';
  ttsSpeed: number = 1.0;
  generatedAudio: any = null;
  isGeneratingSpeech: boolean = false;

  // 图像生成相关
  generatePrompt: string = '';
  generateStyle: string = 'realistic';
  generateSize: string = 'square';
  generateQuality: string = 'standard';
  generatedImages: any[] = [];
  isGenerating: boolean = false;
  generationTime: number = 0;

  // 标签页配置
  tabs = [
    { key: 'chat', label: '智能对话', icon: 'MessageCircle' },
    { key: 'image', label: '图像识别', icon: 'Camera' },
    { key: 'voice', label: '语音处理', icon: 'Mic' },
    { key: 'generate', label: '图像生成', icon: 'Sparkles' }
  ];

  // 图像识别选项
  imageOptions = [
    { key: 'general', label: '通用识别', icon: 'Eye' },
    { key: 'product', label: '产品识别', icon: 'Package' },
    { key: 'symptoms', label: '症状识别', icon: 'Stethoscope' }
  ];

  // 方法
  async sendMessage(message?: string) {
    const messageText = message || this.chatInput.trim();
    if (!messageText) return;
    
    // 添加用户消息
    const userMessage = {
      id: Date.now(),
      role: 'user',
      content: messageText,
      timestamp: new Date().toISOString()
    };
    
    this.chatMessages.push(userMessage);
    this.chatInput = '';
    this.isTyping = true;
  
    try {
      // 构建对话上下文
      const context = {
        user_id: 'current_user',
        session_id: 'current_session',
        messages: this.chatMessages.map(msg => ({
          role: msg.role,
          content: msg.content,
          timestamp: msg.timestamp
        }))
      };
      
      const response = await multimodalAIService.intelligentChat(context, messageText);
      
      // 添加AI回复
      const aiMessage = {
        id: Date.now() + 1,
        role: 'assistant',
        content: response.reply,
        timestamp: new Date().toISOString(),
        suggestions: response.suggestions,
        followUpQuestions: response.follow_up_questions
      };
      
      this.chatMessages.push(aiMessage);
    } catch (error) {
      console.error('发送消息失败:', error);
      toast.error('发送消息失败，请重试');
    } finally {
      this.isTyping = false;
      await this.$nextTick();
      this.scrollToBottom();
    }
  }

  scrollToBottom() {
    const chatContainer = document.querySelector('.chat-messages');
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  }

  async toggleVoiceRecording() {
    if (this.isRecording) {
      this.stopRecording();
    } else {
      await this.startRecording();
    }
  }

  async startRecording() {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      this.mediaRecorder = new MediaRecorder(stream);
      this.audioChunks = [];
      
      this.mediaRecorder.ondataavailable = (event: BlobEvent) => {
        this.audioChunks.push(event.data);
      };
      
      this.mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
        await this.processVoiceInput(audioBlob);
      };
      
      this.mediaRecorder.start();
      this.isRecording = true;
      this.recordingTime = 0;
      
      this.recordingInterval = setInterval(() => {
        this.recordingTime += 1;
      }, 1000);
    } catch (error) {
      console.error('开始录音失败:', error);
      toast.error('无法访问麦克风');
    }
  }

  stopRecording() {
    if (this.mediaRecorder && this.isRecording) {
      this.mediaRecorder.stop();
      this.isRecording = false;
      
      if (this.recordingInterval) {
        clearInterval(this.recordingInterval);
        this.recordingInterval = null;
      }
      
      // 停止所有音频轨道
      (this.mediaRecorder as any).stream.getTracks().forEach((track: MediaStreamTrack) => track.stop());
    }
  }

  async processVoiceInput(audioBlob: Blob) {
    try {
      this.isProcessingVoice = true;
      const audioFile = new File([audioBlob], 'recording.wav', { type: 'audio/wav' });
      const result = await multimodalAIService.speechToText(audioFile, this.voiceLanguage);
      
      if (result.transcript) {
        this.chatInput = result.transcript;
        await this.sendMessage();
      }
    } catch (error) {
      console.error('语音处理失败:', error);
      toast.error('语音识别失败');
    } finally {
      this.isProcessingVoice = false;
      this.recordingTime = 0;
    }
  }

  triggerImageUpload() {
    (this.$refs.imageInput as HTMLInputElement)?.click();
  }

  handleImageUpload(event: Event) {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.selectedImage = e.target?.result as string;
      };
      reader.readAsDataURL(file);
    }
  }

  handleImageDrop(event: DragEvent) {
    event.preventDefault();
    const file = event.dataTransfer?.files[0];
    if (file && file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.selectedImage = e.target?.result as string;
      };
      reader.readAsDataURL(file);
    }
  }

  removeImage() {
    this.selectedImage = null;
    this.imageResult = null;
    const imageInput = this.$refs.imageInput as HTMLInputElement;
    if (imageInput) {
      imageInput.value = '';
    }
  }

  async analyzeImage() {
    if (!this.selectedImage) return;
    
    try {
      this.isAnalyzing = true;
      
      // 将base64转换为File对象
      const response = await fetch(this.selectedImage);
      const blob = await response.blob();
      const file = new File([blob], 'image.jpg', { type: 'image/jpeg' });
      
      let result;
      switch (this.selectedImageOption) {
        case 'product':
          result = await multimodalAIService.recognizeProduct(file);
          break;
        case 'symptoms':
          result = await multimodalAIService.recognizeSymptoms(file);
          break;
        default:
          result = await multimodalAIService.recognizeImage(file);
      }
      
      this.imageResult = result;
    } catch (error) {
      console.error('图像分析失败:', error);
      toast.error('图像分析失败');
    } finally {
      this.isAnalyzing = false;
    }
  }

  async toggleRecording() {
    if (this.isRecording) {
      this.stopRecording();
    } else {
      await this.startVoiceRecording();
    }
  }

  async startVoiceRecording() {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      this.mediaRecorder = new MediaRecorder(stream);
      this.audioChunks = [];
      
      this.mediaRecorder.ondataavailable = (event: BlobEvent) => {
        this.audioChunks.push(event.data);
      };
      
      this.mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
        await this.processVoiceRecording(audioBlob);
      };
      
      this.mediaRecorder.start();
      this.isRecording = true;
      this.recordingTime = 0;
      
      this.recordingInterval = setInterval(() => {
        this.recordingTime += 1;
      }, 1000);
    } catch (error) {
      console.error('开始录音失败:', error);
      toast.error('无法访问麦克风');
    }
  }

  async processVoiceRecording(audioBlob: Blob) {
    try {
      this.isProcessingVoice = true;
      const audioFile = new File([audioBlob], 'recording.wav', { type: 'audio/wav' });
      const result = await multimodalAIService.speechToText(audioFile, this.voiceLanguage);
      this.voiceResult = result;
    } catch (error) {
      console.error('语音处理失败:', error);
      toast.error('语音识别失败');
    } finally {
      this.isProcessingVoice = false;
      this.recordingTime = 0;
    }
  }

  async generateSpeech() {
    if (!this.ttsText.trim()) return;
    
    try {
      this.isGeneratingSpeech = true;
      const result = await multimodalAIService.textToSpeech({
        text: this.ttsText,
        voice: this.ttsVoice,
        speed: this.ttsSpeed,
        pitch: 1.0,
        language: 'zh-CN'
      });
      
      this.generatedAudio = result;
    } catch (error) {
      console.error('语音生成失败:', error);
      toast.error('语音生成失败');
    } finally {
      this.isGeneratingSpeech = false;
    }
  }

  async generateImage() {
    if (!this.generatePrompt.trim()) return;
    
    try {
      this.isGenerating = true;
      const startTime = Date.now();
      
      const result = await multimodalAIService.generateImage({
        prompt: this.generatePrompt,
        style: this.generateStyle as any,
        size: this.generateSize as any,
        quality: this.generateQuality as any,
        count: 1
      });
      
      this.generatedImages = result.images;
      this.generationTime = (Date.now() - startTime) / 1000;
    } catch (error) {
      console.error('图像生成失败:', error);
      toast.error('图像生成失败');
    } finally {
      this.isGenerating = false;
    }
  }

  downloadImage(url: string) {
    const link = document.createElement('a');
    link.href = url;
    link.download = `generated-image-${Date.now()}.jpg`;
    link.click();
  }

  async shareImage(url: string) {
    if (navigator.share) {
      try {
        await navigator.share({
          title: 'AI生成图像',
          url: url
        });
      } catch (error) {
        console.error('分享失败:', error);
      }
    } else {
      // 复制链接到剪贴板
      await navigator.clipboard.writeText(url);
      toast.success('链接已复制到剪贴板');
    }
  }

  // 工具方法
  formatTime(timestamp: string | number) {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }

  formatRecordingTime(seconds: number) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }

  getSeverityText(severity: string) {
    const severityMap: Record<string, string> = {
      mild: '轻微',
      moderate: '中等',
      severe: '严重'
    };
    return severityMap[severity] || severity;
  }

  // 生命周期
  mounted() {
    // 添加欢迎消息
    this.chatMessages.push({
      id: 1,
      role: 'assistant',
      content: '您好！我是您的AI智能助手，专门为您提供母婴护理方面的专业建议。您可以通过文字、语音或图片与我交流，我会尽力为您解答各种育儿问题。',
      timestamp: new Date().toISOString(),
      suggestions: [
        '宝宝喂养问题',
        '睡眠护理建议',
        '产品推荐咨询',
        '健康状况咨询'
      ]
    });
  }
}
</script>

<style scoped>
.ai-assistant {
  @apply min-h-screen bg-gray-50 p-6;
}

.page-header {
  @apply mb-8;
}

.page-title {
  @apply text-3xl font-bold text-gray-900 mb-2;
}

.page-subtitle {
  @apply text-lg text-gray-600;
}

.function-nav {
  @apply mb-8;
}

.nav-tabs {
  @apply flex space-x-1 bg-gray-100 p-1 rounded-lg;
}

.nav-tab {
  @apply flex items-center space-x-2 px-4 py-2 rounded-md text-sm font-medium transition-colors;
}

.nav-tab:not(.active) {
  @apply text-gray-600 hover:text-gray-900 hover:bg-white;
}

.nav-tab.active {
  @apply bg-white text-blue-600 shadow-sm;
}

.content-area {
  @apply bg-white rounded-lg shadow-sm border border-gray-200;
}

.tab-content {
  @apply p-6;
}

/* 聊天界面样式 */
.chat-container {
  @apply flex flex-col h-[600px];
}

.chat-messages {
  @apply flex-1 overflow-y-auto space-y-4 mb-4 p-4 bg-gray-50 rounded-lg;
}

.message {
  @apply flex space-x-3;
}

.message.user {
  @apply flex-row-reverse space-x-reverse;
}

.message-avatar {
  @apply w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center flex-shrink-0;
}

.message.user .message-avatar {
  @apply bg-blue-500 text-white;
}

.message.assistant .message-avatar {
  @apply bg-green-500 text-white;
}

.message-content {
  @apply flex-1 max-w-[80%];
}

.message.user .message-content {
  @apply text-right;
}

.message-text {
  @apply bg-white p-3 rounded-lg shadow-sm border border-gray-200 mb-1;
}

.message.user .message-text {
  @apply bg-blue-500 text-white;
}

.message-time {
  @apply text-xs text-gray-500;
}

.message-suggestions {
  @apply flex flex-wrap gap-2 mt-2;
}

.suggestion-btn {
  @apply px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm hover:bg-blue-200 transition-colors;
}

.typing {
  @apply opacity-70;
}

.typing-indicator {
  @apply flex space-x-1 p-3;
}

.typing-indicator span {
  @apply w-2 h-2 bg-gray-400 rounded-full animate-bounce;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.1s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.2s;
}

.chat-input-area {
  @apply border-t border-gray-200 pt-4;
}

.input-container {
  @apply flex items-center space-x-2;
}

.chat-input {
  @apply flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
}

.voice-btn {
  @apply p-2 text-gray-500 hover:text-blue-500 rounded-lg hover:bg-gray-100 transition-colors;
}

.voice-btn.recording {
  @apply text-red-500 bg-red-50;
}

.send-btn {
  @apply p-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
}

/* 图像识别样式 */
.image-recognition {
  @apply space-y-6;
}

.upload-area {
  @apply mb-6;
}

.upload-zone {
  @apply border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-blue-400 transition-colors relative;
}

.upload-placeholder {
  @apply flex flex-col items-center;
}

.image-preview {
  @apply relative;
}

.preview-img {
  @apply max-w-full max-h-64 rounded-lg;
}

.remove-image {
  @apply absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-600 transition-colors;
}

.recognition-options {
  @apply flex items-center justify-between mb-6;
}

.option-tabs {
  @apply flex space-x-2;
}

.option-tab {
  @apply flex items-center space-x-2 px-3 py-2 rounded-md text-sm font-medium transition-colors;
}

.option-tab:not(.active) {
  @apply text-gray-600 bg-gray-100 hover:bg-gray-200;
}

.option-tab.active {
  @apply bg-blue-500 text-white;
}

.analyze-btn {
  @apply flex items-center space-x-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
}

.analysis-result {
  @apply bg-gray-50 rounded-lg p-6;
}

.result-title {
  @apply text-xl font-semibold text-gray-900 mb-4;
}

.result-content {
  @apply space-y-6;
}

.section-title {
  @apply text-lg font-medium text-gray-900 mb-3;
}

.objects-grid {
  @apply grid grid-cols-2 md:grid-cols-3 gap-3;
}

.object-item {
  @apply flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200;
}

.object-name {
  @apply font-medium text-gray-900;
}

.object-confidence {
  @apply text-sm text-green-600;
}

.scene-description {
  @apply text-gray-700 mb-3;
}

.scene-tags {
  @apply flex flex-wrap gap-2;
}

.scene-tag {
  @apply px-2 py-1 bg-blue-100 text-blue-800 text-sm rounded-full;
}

.product-info {
  @apply mb-6;
}

.product-name {
  @apply text-xl font-bold text-gray-900 mb-2;
}

.product-category,
.product-brand,
.product-confidence {
  @apply text-gray-600 mb-1;
}

.products-grid {
  @apply grid grid-cols-1 md:grid-cols-2 gap-4;
}

.product-card {
  @apply flex space-x-3 p-4 bg-white rounded-lg border border-gray-200;
}

.product-image {
  @apply w-16 h-16 rounded-lg object-cover;
}

.product-details {
  @apply flex-1;
}

.product-title {
  @apply font-medium text-gray-900 mb-1;
}

.product-price {
  @apply text-green-600 font-semibold mb-1;
}

.product-rating {
  @apply flex items-center space-x-1 text-sm text-gray-600;
}

.safety-info {
  @apply bg-blue-50 p-4 rounded-lg;
}

.safety-age,
.safety-rating {
  @apply text-gray-700 mb-2;
}

.warnings-title {
  @apply font-medium text-gray-900 mb-2;
}

.warnings-list {
  @apply list-disc list-inside space-y-1 text-gray-700;
}

.urgent-warning {
  @apply flex items-center space-x-2 p-4 bg-red-50 border border-red-200 rounded-lg mb-4;
}

.urgent-text {
  @apply text-red-700 font-semibold;
}

.conditions-list {
  @apply space-y-4;
}

.condition-item {
  @apply p-4 bg-white rounded-lg border border-gray-200;
}

.condition-header {
  @apply flex items-center justify-between mb-2;
}

.condition-name {
  @apply font-semibold text-gray-900;
}

.severity-badge {
  @apply px-2 py-1 rounded-full text-xs font-medium;
}

.severity-badge.mild {
  @apply bg-green-100 text-green-800;
}

.severity-badge.moderate {
  @apply bg-yellow-100 text-yellow-800;
}

.severity-badge.severe {
  @apply bg-red-100 text-red-800;
}

.condition-description {
  @apply text-gray-700 mb-3;
}

.recommendations-title {
  @apply font-medium text-gray-900 mb-2;
}

.recommendations-list {
  @apply list-disc list-inside space-y-1 text-gray-700;
}

.disclaimer {
  @apply flex items-start space-x-2 p-4 bg-blue-50 border border-blue-200 rounded-lg;
}

.disclaimer-text {
  @apply text-blue-700 text-sm;
}

/* 语音处理样式 */
.voice-processing {
  @apply space-y-8;
}

.voice-recorder {
  @apply text-center;
}

.recorder-container {
  @apply space-y-4;
}

.record-button {
  @apply w-20 h-20 rounded-full bg-blue-500 text-white flex items-center justify-center cursor-pointer hover:bg-blue-600 transition-colors mx-auto;
}

.record-button.recording {
  @apply bg-red-500 hover:bg-red-600 animate-pulse;
}

.record-button.processing {
  @apply bg-yellow-500 hover:bg-yellow-600;
}

.record-status {
  @apply text-lg text-gray-700;
}

.recording-time {
  @apply text-2xl font-mono text-red-600;
}

.voice-options {
  @apply flex justify-center;
}

.option-group {
  @apply space-y-2;
}

.option-label {
  @apply block text-sm font-medium text-gray-700;
}

.option-select {
  @apply px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
}

.voice-result {
  @apply bg-gray-50 rounded-lg p-6;
}

.transcript-container {
  @apply mb-4;
}

.transcript-text {
  @apply text-lg text-gray-900 mb-2;
}

.transcript-confidence {
  @apply text-sm text-green-600;
}

.segments-container {
  @apply space-y-3;
}

.segments-title {
  @apply text-lg font-medium text-gray-900 mb-3;
}

.segments-list {
  @apply space-y-2;
}

.segment-item {
  @apply flex items-center space-x-3 p-3 bg-white rounded-lg border border-gray-200;
}

.segment-time {
  @apply text-sm text-gray-500 font-mono;
}

.segment-text {
  @apply flex-1 text-gray-900;
}

.tts-section {
  @apply border-t border-gray-200 pt-8;
}

.tts-input-area {
  @apply space-y-4;
}

.tts-textarea {
  @apply w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none;
  height: 120px;
}

.tts-options {
  @apply flex space-x-6;
}

.option-range {
  @apply w-24;
}

.range-value {
  @apply text-sm text-gray-600 ml-2;
}

.generate-speech-btn {
  @apply flex items-center space-x-2 px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
}

.audio-player {
  @apply space-y-2;
}

.audio-control {
  @apply w-full;
}

.audio-info {
  @apply text-sm text-gray-600;
}

/* 图像生成样式 */
.image-generation {
  @apply space-y-6;
}

.generation-form {
  @apply space-y-4;
}

.form-group {
  @apply space-y-2;
}

.form-label {
  @apply block text-sm font-medium text-gray-700;
}

.form-textarea {
  @apply w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none;
  height: 100px;
}

.form-row {
  @apply grid grid-cols-1 md:grid-cols-3 gap-4;
}

.form-select {
  @apply px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
}

.generate-btn {
  @apply flex items-center space-x-2 px-6 py-3 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-lg hover:from-purple-600 hover:to-pink-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
}

.generated-images {
  @apply space-y-4;
}

.images-grid {
  @apply grid grid-cols-1 md:grid-cols-2 gap-6;
}

.generated-image {
  @apply space-y-3;
}

.generated-img {
  @apply w-full rounded-lg shadow-md;
}

.image-actions {
  @apply flex space-x-2;
}

.action-btn {
  @apply flex items-center space-x-1 px-3 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors;
}

.generation-info {
  @apply text-sm text-gray-600;
}
</style>